import { useEffect } from "react";
import { Editor } from "@tinymce/tinymce-react";
import { uploadApi } from "@/apis/upload";

export default function PostEdit({ post, setPost }: any) {
  function editorChange(content: any) {
    setPost({ ...post, content: content });
  }

  useEffect(() => {
    return () => {
      setPost({ title: "", content: "" });
    };
  }, []);

  return (
    <Editor
      tinymceScriptSrc="/tinymce/tinymce.min.js"
      init={init}
      value={post.content}
      onEditorChange={editorChange}
      licenseKey="gpl"
    />
  );
}

async function upload(blobInfo: any /* , progress: any */) {
  try {
    const res: any = await uploadApi(blobInfo.blob());
    if (res.code === 0) {
      return res.data;
    } else {
      throw new Error("上传失败: " + res.message);
    }
  } catch (error: any) {
    throw new Error("上传失败: " + (error.message || error));
  }
}

const init = {
  language: "zh_CN",
  language_url: "/tinymce/langs/zh_CN.js",
  placeholder: "请输入内容...",
  height: 500,
  width: "100%",
  branding: false,
  promotion: false,
  highlight_on_focus: false,
  images_upload_handler: upload,
  plugins: [
    "advlist",
    "autolink",
    "lists",
    "link",
    "image",
    "charmap",
    "preview",
    "anchor",
    "searchreplace",
    "visualblocks",
    "code",
    "fullscreen",
    "insertdatetime",
    "media",
    "table",
    "code",
    "help",
    "wordcount",
  ],
  toolbar:
    "undo redo | styles | " +
    "bold italic forecolor | alignleft aligncenter " +
    "alignright alignjustify | bullist numlist outdent indent | " +
    "removeformat | help",
  content_style:
    "body { font-family:Helvetica,Arial,sans-serif; font-size:14px }",
};
